package dproxy.server.concurrent;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;


/**
 * Creates threads or gets them from thread pool.
 */
public class ThreadManager {

    /** Singleton instance. */
    private static ThreadManager instance = new ThreadManager();;
    
    /** Thread pool for this application. */
    private ExecutorService executor;
    
    /**
     * Protected constructor.
     */
    protected ThreadManager() {
        executor = Executors.newCachedThreadPool();
    }
    
    /**
     * @return Singleton Instance
     */
    public static ThreadManager getInstance() {
        return instance;
    }
    
    /**
     * Runs the process in a newly created thread.
     * @param name Thread name
     * @param runnable runnable
     */
    public void runInNewThread(Runnable runnable, String name) {
        Thread thread = new Thread(runnable, name);
        thread.start();
    }
    
    /**
     * Runs the process in a thread from Thread Pool.
     * @param runnable runnable
     */
    public void runInThreadFromPool(Runnable runnable) {
        executor.execute(runnable);
    }
    
    /**
     * Closes all threads from pool.
     */
    public void shutdown() {
        executor.shutdown();
    }
}
